package com.mapforge.map.tools.tilewriting;

import java.awt.Point;
import java.awt.Rectangle;

import com.mapforge.map.tilewriter.TileWriter;
import com.mapforge.selection.ContinuousSelection;
import com.mapforge.selection.Selection;

/** */
public class RectangleTool extends AbstractShapeTileWriterTool {

	public RectangleTool() {
		super("Rectangle tool");
	}

	@Override
	public void beginEdit() {
		super.beginEdit();
		this.getTileWriter().beginPreview();
		this.makeSelection();
	}

	public void performEdit() {
		this.makeSelection();
	}

	public void endEdit() {
		super.endEdit();
		this.validateState();
		this.makeSelection();
		this.getTileWriter().endPreview();
		Selection destination = this.getCurrentSelection();
		TileWriter tilewriter = getTileWriter();
		tilewriter.beginWrite();
		tilewriter.writeTiles(getTileSelection(), destination);
		tilewriter.endWrite();
	}

	@Override
	public Selection performSelection(Point startPoint, Point currentPoint) {
		int x, y, w, h;
		if (startPoint.x >= currentPoint.x) {
			x = currentPoint.x;
			w = startPoint.x - x;
		} else {
			x = startPoint.x;
			w = currentPoint.x - x;
		}
		if (startPoint.y >= currentPoint.y) {
			y = currentPoint.y;
			h = startPoint.y - y;
		} else {
			y = startPoint.y;
			h = currentPoint.y - y;
		}

		Rectangle r = new Rectangle(x, y, w + 1, h + 1);
		return new ContinuousSelection(r);
	}
}
